import os
import sys
import websockets
import asyncio
import json
import sqlite3
import volleyball_detection
from volleyball_detection import process_video


# 将当前目录添加到 Python 的搜索路径中
current_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.append(current_dir)

from flask import Flask, request, jsonify, send_file
from flask_websockets import WebSockets
from flask_websockets.websocket import WebSocketState
from datetime import datetime
from app import init_db,app
websockets = WebSockets(app)
# 视频保存目录
UPLOAD_FOLDER = 'uploads'
if not os.path.exists(UPLOAD_FOLDER):
    os.makedirs(UPLOAD_FOLDER)

# 确保session目录存在
SESSION_FOLDER = 'sessions'
if not os.path.exists(SESSION_FOLDER):
    os.makedirs(SESSION_FOLDER)

websocket_connection=None

# 添加一个全局变量来存储检测区域参数
detection_zone_params = {
    'top': 0.1,
    'left': 0.2,
    'bottom': 0.3,
    'right': 0.7
}

@app.route('/')
def index():
    return send_file('index.html')

@app.route('/create_session', methods=['POST'])
def create_session():
    session_id = datetime.now().strftime('%Y%m%d_%H%M%S')
    return jsonify({'session_id': session_id})

@app.route('/upload_chunk', methods=['POST'])
def upload_chunk():
    if 'chunk' not in request.files:
        return jsonify({'error': '没有文件'}), 400
        
    chunk = request.files['chunk']
    session_id = request.form.get('session_id')
    
    if not session_id:
        return jsonify({'error': '无效的会话ID'}), 400
    
    # 保存chunk
    chunk_path = os.path.join(SESSION_FOLDER, f'{session_id}_{len(os.listdir(SESSION_FOLDER))}.mp4')
    out_path = os.path.join(SESSION_FOLDER, f'o{session_id}_{len(os.listdir(SESSION_FOLDER))}.mp4')
    chunk.save(chunk_path)
    from volleyball_detection import process_video
    process_video(chunk_path, out_path, 
                 top=detection_zone_params['top'],
                 left=detection_zone_params['left'],
                 bottom=detection_zone_params['bottom'],
                 right=detection_zone_params['right'])
    
    return jsonify({'status': 'success'})

@app.route('/complete_session', methods=['POST'])
def complete_session():
    data = request.get_json()
    session_id = data.get('session_id')
    
    if not session_id:
        return jsonify({'error': '无效的会话ID'}), 400
    
    try:
        # 合并所有chunks
        chunks = [f for f in os.listdir(SESSION_FOLDER) if f.startswith(session_id)]
        if not chunks:
            return jsonify({'error': '没有视频数据'}), 400
            
        output_path = os.path.join(UPLOAD_FOLDER, f'{session_id}.mp4')
        with open(output_path, 'wb') as outfile:
            for chunk_name in sorted(chunks):
                chunk_path = os.path.join(SESSION_FOLDER, chunk_name)
                with open(chunk_path, 'rb') as infile:
                    outfile.write(infile.read())
                # 删除临时chunk文件
                os.remove(chunk_path)
        
        return jsonify({'status': 'success', 'message': '视频上传完成'})
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/update_detection_zone', methods=['POST'])
def update_detection_zone():
    global detection_zone_params
    try:
        data = request.json
        detection_zone_params = {
            'top': float(data.get('top', 0.1)),
            'left': float(data.get('left', 0.2)),
            'bottom': float(data.get('bottom', 0.3)),
            'right': float(data.get('right', 0.7))
        }
        return jsonify({'status': 'success', 'params': detection_zone_params})
    except Exception as e:
        return jsonify({'status': 'error', 'message': str(e)}), 400

# WebSocket连接处理
@websockets.route('/ws')
def handle_websocket(ws):
    try:
        while ws.state == WebSocketState.CONNECTED:
        # 接收客户端消息
            message = ws.receive()
            data = json.loads(message)
            datatype = data['type']
            if datatype == 'start_playback':
                record_id = data['record_id']
                # 获取测试记录
                conn = sqlite3.connect('volleyball.db')
                c = conn.cursor()
                record = c.execute('SELECT * FROM test_records WHERE id = ?', (record_id,)).fetchone()
                conn.close()
                
                if not record:
                    ws.send(json.dumps({
                        'type': 'error',
                        'message': '未找到测试记录'
                    }))
                    continue
                
                video_path = record[6]  # video_path is the 7th column
                if not video_path or not os.path.exists(video_path):
                    ws.send(json.dumps({
                        'type': 'error',
                        'message': '视频文件不存在'
                    }))
                    continue
                volleyball_detection.counter_enable = True
                # 获取计数数据
                counter_data = process_video(video_path, websocket=ws,
                                          top=detection_zone_params['top'],
                                          left=detection_zone_params['left'],
                                          bottom=detection_zone_params['bottom'],
                                          right=detection_zone_params['right'])
                volleyball_detection.counter_enable = False
            elif datatype == 'start_check':
                volleyball_detection.counter_enable = True
                video_path = os.path.join('uploads', f"{data['filename']}.mp4")
                source = "uploads/527_1742982375.mp4"
                # source = 0
                counter_data = process_video(source,websocket=ws,output_path=video_path)
                volleyball_detection.counter_enable = False
            elif datatype == 'stop_playback':
                volleyball_detection.counter_enable = False

    except Exception as e:
        print(f"WebSocket错误: {str(e)}")
        try:
            ws.send(json.dumps({
                'type': 'error',
                'message': str(e)
            }))
        except:
            pass
    finally:
        websocket_connection = None


if __name__ == '__main__':
    init_db()
    app.run(debug=True,port=5000) 